package controllers

// 不进行任何验证,用于登录,api版本查看等用途
import (
	"database/sql"
	"html"
	"io/ioutil"
	"strings"
	"time"
	"devOpsApi/base"
	"devOpsApi/middleware"
	"devOpsApi/model"
	"github.com/bitly/go-simplejson"
	"github.com/kataras/iris"
)

type IndexController struct {
	base.BController
}

// 登录
func (c *IndexController) PostPlatFormLogin() {
	userName := html.EscapeString(c.Ctx.PostValueDefault("username", ""))
	password := html.EscapeString(c.Ctx.PostValueDefault("password", ""))
	if userName == "" || password == "" {
		c.OutDataJson("", iris.StatusBadRequest, "账号和密码不能为空!")
		return
	}

	// 注册用户查询
	UserModel := model.NewUser()
	UserDb, err := UserModel.LoginCheck(userName, password)
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	if UserDb.Status.Int64 != 0 {
		c.OutDataJson("", iris.StatusBadRequest, "账号处于待审核,或禁用状态!")
		return
	}
	UserDb.Token = middleware.GetUserToken(UserDb.UserId)
	RoleId, RoleName := UserModel.GetUser2Role(uint(UserDb.ID))
	UserDb.RoleId = RoleId
	UserDb.RoleName = RoleName
	UserDb.Pwd = ""
	c.OutDataJson(UserDb, iris.StatusOK, "success")
	return
}

// 注册
func (c *IndexController) PostReg() {
	user := model.NewUser()
	err := c.Ctx.ReadForm(user)
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	user.Form = 2
	user.Status = sql.NullInt64{Int64: 0, Valid: true}
	newUser, err := user.Create()
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	c.OutDataJson(newUser, iris.StatusOK, "success")
}

// 运行流水线 内部任务
// 只执行merge 到 master分支
// http://localhost:8005/v1/run/18
func (c *IndexController) PostRunBy(id uint) {
	data, err := ioutil.ReadAll(c.Ctx.Request().Body)
	if err != nil {
		return
	}
	dataJson, err := simplejson.NewJson(data)
	if err != nil {
		return
	}
	object_kind, err := dataJson.GetPath("object_kind").String()
	if err != nil {
		return
	}
	if object_kind != "merge_request" {
		return
	}
	object_attributes, err := dataJson.GetPath("object_attributes").Map()
	if err != nil {
		return
	}
	if _, ok := object_attributes["target_branch"]; !ok {
		return
	}
	if object_attributes["target_branch"] != "master" {
		//return
	}
	GitlabToken := c.Ctx.GetHeader("X-Gitlab-Token")
	pipelineModel := model.NewPipeline()
	pipeline, err := pipelineModel.DetailAnyOne(id)
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}

	//支持多分支
	if pipeline.Branch != object_attributes["target_branch"] {
		return
	}

	if pipeline.GitLabSecret != GitlabToken {
		c.OutDataJson("", iris.StatusBadRequest, "Token 验证错误")
		return
	}
	now := time.Now()
	err = pipelineModel.UpdateFieldsAnyOne(id, map[string]interface{}{"last_build": now})
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	pipeline.LastBuild = &now
	go func() {
		var Pipeline PipelineController
		runType := make(map[string]string)
		runType["type"] = "all" // all:全部执行 step:单点执行 persion:人工卡点,往后执行
		runType["position"] = ""
		Pipeline.RunPipeline(pipeline, "auto", runType)
	}()
	c.OutDataJson("", iris.StatusOK, "success")
	return
}

func (c *IndexController) PostRunGiteeBy(id uint) {
	data, err := ioutil.ReadAll(c.Ctx.Request().Body)
	if err != nil {
		return
	}
	dataJson, err := simplejson.NewJson(data)
	if err != nil {
		return
	}
	hookName, err := dataJson.GetPath("hook_name").String()
	if err != nil {
		return
	}
	if hookName != "push_hooks" {
		return
	}

	//分支
	ref, err := dataJson.GetPath("ref").String()
	if err != nil {
		return
	}

	ref = strings.Replace(ref, "refs/heads/", "", -1)
	if ref != "master" {
		return
	}

	pipelineModel := model.NewPipeline()
	pipeline, err := pipelineModel.DetailAnyOne(id)
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}

	//支持多分支
	if pipeline.Branch != ref {
		return
	}

	//https://gitee.com/help/articles/4290#article-header0
	GitlabToken := c.Ctx.GetHeader("X-Gitee-Token")
	if pipeline.GitLabSecret != GitlabToken {
		c.OutDataJson("", iris.StatusBadRequest, "Token 验证错误")
		return
	}
	now := time.Now()
	err = pipelineModel.UpdateFieldsAnyOne(id, map[string]interface{}{"last_build": now})
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	pipeline.LastBuild = &now
	go func() {
		var Pipeline PipelineController
		runType := make(map[string]string)
		runType["type"] = "all" // all:全部执行 step:单点执行 persion:人工卡点,往后执行
		runType["position"] = ""
		Pipeline.RunPipeline(pipeline, "auto", runType)
	}()
	c.OutDataJson("", iris.StatusOK, "success")
	return
}

//gituhb
func (c *IndexController) PostRunGithubBy(id uint) {
	data, err := ioutil.ReadAll(c.Ctx.Request().Body)
	if err != nil {
		return
	}
	dataJson, err := simplejson.NewJson(data)
	if err != nil {
		return
	}

	//分支
	ref, err := dataJson.GetPath("ref").String()
	if err != nil {
		return
	}
	ref = strings.Replace(ref, "refs/heads/", "", -1)
	if ref != "master" {
		return
	}

	//token验证
	GitlabToken := c.Ctx.URLParamDefault("token", "")
	pipelineModel := model.NewPipeline()
	pipeline, err := pipelineModel.DetailAnyOne(id)
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}

	//支持多分支
	if pipeline.Branch != ref {
		return
	}

	if pipeline.GitLabSecret != GitlabToken {
		c.OutDataJson("", iris.StatusBadRequest, "Token 验证错误")
		return
	}
	now := time.Now()
	err = pipelineModel.UpdateFieldsAnyOne(id, map[string]interface{}{"last_build": now})
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	pipeline.LastBuild = &now
	go func() {
		var Pipeline PipelineController
		runType := make(map[string]string)
		runType["type"] = "all" // all:全部执行 step:单点执行 persion:人工卡点,往后执行
		runType["position"] = ""
		Pipeline.RunPipeline(pipeline, "auto", runType)
	}()
	c.OutDataJson("", iris.StatusOK, "success")
	return
}